/*Author: Rony Lahav (ID:043489889)*/

import java.util.Collection;
import java.util.TreeMap;


public class StatusManagerSN extends StatusManager implements Runnable{
	public void run(){
		do{
			// Get from the DB all of the tuples to which I should check status
			TreeMap<String,DBTuple> peersForAV = (TreeMap<String,DBTuple>)DataBase.getInstance().getAllOnlineRegTuples();
			long currentTime=System.currentTimeMillis();
			//run over all peers and check if they need to become offline
			Collection<DBTuple> c = peersForAV.values();
			for (DBTuple tuple : c) {
				if (final_project.isShutDown()) {
					break;
				}
				if ((tuple.getLastConnectionTime()+final_project.timeout)<=currentTime){	//peer needs to become offline
					tuple.setStatus("0");
				}
			}
			// Get from the DB all of the tuples to which I should check status
			TreeMap<String,DBTuple> snsForAV = (TreeMap<String,DBTuple>)DataBase.getInstance().getAllOnlineSNTuples();
			//run over all peers and check if they need to become offline
			c = snsForAV.values();
			for (DBTuple sn : c) {
				if (final_project.isShutDown()) {
					break;
				}
				if ((sn.getLastConnectionTime()+final_project.timeout)<=currentTime){	//SN needs to become offline
					sn.setStatus("0");
					if (sn.ConnectedThrough().equals(final_project.getMyKey())){	//if i was the direct link to the SN contact his SNs
						sn.setConnectedThrough("0");
						long id = final_project.getNewUniqueID();
						DisconnectedSNHandler handleDisconnection = new DisconnectedSNHandler(sn, id);
						Thread thread = new Thread(handleDisconnection);
						final_project.addThreadToLivingList(id, thread);
						thread.start();
					}
					else
						sn.setConnectedThrough("0");
				}
			}
			try{
				// Sleep until next update frequency
				Thread.sleep(final_project.frequency);
			}
			catch (InterruptedException e){}
		} while (!final_project.isShutDown());
	}
}
